package com.nxmu.hire.controller;

import com.github.pagehelper.PageInfo;
import com.nxmu.hire.common.exception.ServiceException;
import com.nxmu.hire.common.util.ResponseResult;
import com.nxmu.hire.model.User;
import com.nxmu.hire.service.TeacherService;
import com.nxmu.hire.vo.FindTeacherReqVo;
import com.nxmu.hire.vo.FindTeacherResVo;
import com.nxmu.hire.vo.ModifyTeacherReqVo;
import com.nxmu.hire.vo.TeacherAddReqVo;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author Lee
 *
 */
@CrossOrigin(origins = "*",allowCredentials = "true")
@RestController
@RequestMapping("/teacher")
public class TeacherController {

	private final static Logger LOGGER = LoggerFactory.getLogger(TeacherController.class);

	@Autowired
	private TeacherService teacherService;

	@ApiOperation(value = "添加教师")
	@PostMapping(value = "/save")
	public ResponseResult save(@Valid @RequestBody TeacherAddReqVo teacherAddReqVo){
		try {
			teacherService.saveTeacher(teacherAddReqVo);
		} catch (ServiceException e) {
			LOGGER.error(e.getMessage());
			return ResponseResult.fail(e.getMessage());
		}
		return ResponseResult.success();
	}

	@ApiOperation(value = "按照编号查询教师信息")
	@GetMapping(value = "/findTeacherByUserId/{userId}")
	public ResponseResult findTeacherByUserId(@PathVariable(name = "userId") String userId) {
		FindTeacherResVo teacherRes = teacherService.findTeacherByUserId(userId);
		return ResponseResult.success(teacherRes);
	}

	@ApiOperation(value = "查询所有教师")
	@PostMapping(value = "/findTeacherByCondition")
	public ResponseResult findByPage(@Valid @RequestBody FindTeacherReqVo findTeacherReqVo) {
		PageInfo<User> teacherByPage = teacherService.findTeacherByPage(findTeacherReqVo);
		return ResponseResult.success(teacherByPage);
	}

	@ApiOperation(value = "根据编号删除教师信息")
	@GetMapping(value = "/deleteById")
	public ResponseResult deleteById(@RequestParam(value = "userId") String userId){
		try {
			teacherService.deleteById(userId);
		} catch (ServiceException e) {
			return ResponseResult.fail(e.getMessage());
		}
		return ResponseResult.success();
	}

	@ApiOperation(value = "修改教师信息")
	@PostMapping(value = "modifyTeacher")
	public ResponseResult modifyTeacher(@Valid @RequestBody ModifyTeacherReqVo modifyTeacherReqVo) {
		User user = new User();
		BeanUtils.copyProperties(modifyTeacherReqVo,user);
		try {
			teacherService.updateTeacher(user);
		} catch (ServiceException e) {
			return ResponseResult.fail(e.getMessage());
		}
		return ResponseResult.success();
	}

}
